//
//  AppDelegate.m
//  QinrenManagers
//
//  Created by lemon on 15/5/22.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "AppDelegate.h"

#import "UIImageView+EMWebCache.h"


//#import "MainViewController.h"
//#import "GroupListViewController.h"
//#import "MineViewController.h"

// 视图控制器
#import "MainViewController.h"
#import "MineViewController.h"
#import "ChatListViewController.h"
#import "ChatListController.h"

#import "CallViewController.h"

#import "MyNavigationController.h"

#import "FriendModel.h"

#import "APService.h"



@interface AppDelegate ()<IChatManagerDelegate,EMCallManagerDelegate,UIScrollViewDelegate>
{
//    ChatListViewController *chatListViewController;
    ChatListController *chatListController;
    MyNavigationController * chatNav;
    //本地推送
    UILocalNotification *_notification;
    UIAlertView *alertQuit;
    
    UIPageControl *pageControl;
    
    BOOL isOut;

}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self registerNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUntreatedApplyCount) name:@"setupUntreatedApplyCount" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOutWithChatter:) name:@"callOutWithChatter" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callControllerClose:) name:@"callControllerClose" object:nil];

 
    // Override point for customization after application launch.
    
    
    /**
     *  enable控制整个功能是否启用。
     
     shouldResignOnTouchOutside控制点击背景是否收起键盘。
     
     shouldToolbarUsesTextFieldTintColor 控制键盘上的工具条文字颜色是否用户自定义。
     
     enableAutoToolbar控制是否显示键盘上的工具条。
     */
    
    
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
  
 //语音播放之切换听筒和扬声器的方法解决方案
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; //建议在播放之前设置yes，播放结束设置NO，这个功能是开启红外感应
    //添加监听
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(sensorStateChange:)
     
                                                 name:@"UIDeviceProximityStateDidChangeNotification"
     
                                               object:nil];
    
    
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
    // Required
    [APService setupWithOption:launchOptions];
    DLog(@"-----%@--",[APService registrationID]);
    

    [self setupNotifiers];

    
    
    /** < 首次登陆引导页 > **/

    isOut =NO;
 
    //在沙盒做一个文件，判断沙盒有没有这个文件
    
    NSString *path1 = NSHomeDirectory();
    
    NSLog(@"path1:%@", path1);
    
//    BOOL isHasFile=[fileManager fileExistsAtPath:[NSHomeDirectory() stringByAppendingString:@""]];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    if ([userDefaults  objectForKey:@"qidong"] != nil)
    {
        [self setupLoginView];
//        [self gotoMain];
    }else {
        [userDefaults setObject:@"qidong" forKey:@"qidong"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self makeLaunchView];
    }
    
//    if (isHasFile) {
//        //为真表示已有文件 曾经进入过主页
//    }else{
//        [self makeLaunchView];//为假表示没有文件，没有进入过主页
//    }

   
    
    [self.window makeKeyAndVisible];
    
    return YES;
}


//假引导页面
-(void)makeLaunchView{
    NSArray *arr=[NSArray arrayWithObjects:@"jiankang.jpg",@"tuandui.jpg",nil];//数组内存放的是我要显示的假引导页面图片
    //通过scrollView 将这些图片添加在上面，从而达到滚动这些图片
    UIScrollView *scr=[[UIScrollView alloc] initWithFrame:self.window.bounds];
    scr.contentSize=CGSizeMake(SCREEN_W*arr.count, SCREEN_H);
    scr.pagingEnabled=YES;
    scr.showsVerticalScrollIndicator = FALSE;
    scr.showsHorizontalScrollIndicator = FALSE;
    scr.tag=7000;
    scr.delegate=self;
    [self.window addSubview:scr];
    for (int i=0; i<arr.count; i++) {
        UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(i*SCREEN_W, 0, SCREEN_W, self.window.frame.size.height)];
        img.image=[UIImage imageNamed:arr[i]];
        [scr addSubview:img];
    }
    
    UIButton *enterButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W+SCREEN_W/2-80, SCREEN_H-100, 160, 50)];
    
    [enterButton setTitle:@"立即进入" forState:UIControlStateNormal];
    [enterButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    // 按钮边框宽度
    enterButton.layer.borderWidth = 1.5;
    // 设置颜色空间为rgb，用于生成ColorRef
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    // 新建一个红色的ColorRef，用于设置边框（四个数字分别是 r, g, b, alpha）
    CGColorRef borderColorRef = CGColorCreate(colorSpace,(CGFloat[]){ 114.0/255,198.0/255,76.0/255 ,1.0});
    // 设置边框颜色
    enterButton.layer.borderColor = borderColorRef;
//    enterButton.backgroundColor = [UIColor yellowColor];
    enterButton.layer.cornerRadius = 5;
    enterButton.clipsToBounds = YES;
    
    [enterButton addTarget:self action:@selector(enterButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [scr addSubview:enterButton];
    
    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(enterButton.frame)-30, SCREEN_W, 20)];
//    [pageControl setBackgroundColor:[UIColor lightGrayColor]];
    
    pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    

   pageControl.currentPage = 0;
    pageControl.numberOfPages = [arr count];
    [self.window addSubview:pageControl];
    
    
}

- (void)enterButtonClick {
     UIScrollView *scrollview = (UIScrollView *)[self.window viewWithTag:7000];
    
    [UIView animateWithDuration:1.0 animations:^{
        scrollview.alpha=0;//让scrollview 渐变消失
        
    }completion:^(BOOL finished) { UIScrollView *scrollview = (UIScrollView *)[self.window viewWithTag:7000];
        [scrollview  removeFromSuperview];//将scrollView移除
        [pageControl removeFromSuperview];
        [self setupLoginView];
        //            [self gotoMain];//进入主界面
        
    } ];


}
#pragma mark scrollView的代理
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //这里是在滚动的时候判断 我滚动到哪张图片了，如果滚动到了最后一张图片，那么
    //如果在往下面滑动的话就该进入到主界面了，我这里利用的是偏移量来判断的，当
    //一共五张图片，所以当图片全部滑完后 又像后多滑了30 的时候就做下一个动作
    if (scrollView.contentOffset.x>SCREEN_W+30) {
        
        isOut=YES;//这是我声明的一个全局变量Bool 类型的，初始值为no，当达到我需求的条件时将值改为yes
        
    }
}
//停止滑动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    UIScrollView *scrollview = (UIScrollView *)[self.window viewWithTag:7000];
    
    CGFloat pageWidth = CGRectGetWidth(scrollview.frame);
    NSInteger page = floor((scrollview.contentOffset.x -pageWidth/2)/pageWidth) +1;
    pageControl.currentPage = page;
    
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    // Required
    [APService registerDeviceToken:deviceToken];
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
    NSLog(@"error -- %@",error);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
//    [self sendPushIfReceiveMessage:[userInfo[@"aps"][@"badge"] integerValue]];
}

//处理监听触发事件

-(void)sensorStateChange:(NSNotificationCenter *)notification;

{
    
    //如果此时手机靠近面部放在耳朵旁，那么声音将通过听筒输出，并将屏幕变暗（省电啊）
    
    if ([[UIDevice currentDevice] proximityState] == YES)
        
    {
        
        NSLog(@"Device is close to user");
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        
        
    }
    
    else
        
    {
        
        NSLog(@"Device is not close to user");
        
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        
    }
    
}



#pragma mark------------------------------首页 登录-------------------------


- (void)setupLoginView
{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    MyNavigationController *navgation = [board instantiateViewControllerWithIdentifier:@"navgation"];
    self.window.rootViewController = navgation;

}

- (void)setupTabbar
{
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:93/255.0 green:152/255.0 blue:253/255.0 alpha:1.0]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    MainViewController * mainViewController = [[MainViewController alloc]init];
    MyNavigationController * mainNav = [[MyNavigationController alloc] initWithRootViewController:mainViewController];
    /*
     导航条透明
     */
    //mainNav.navigationBar.translucent = NO;
    mainViewController.navigationItem.title = @"首页";
    mainNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"首页" image:[UIImage imageNamed:@"shouye_"] selectedImage:[UIImage imageNamed:@"shouye_1"]];
    
    
//    chatListViewController = [[ChatListViewController alloc]init];
//    chatNav = [[MyNavigationController alloc] initWithRootViewController:chatListViewController];
//    chatListViewController.navigationItem.title = @"交流群";
//    //chatListViewController.setUnreadCountDelegate = self;
//    chatNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"交流群" image:[UIImage imageNamed:@"jiaoliu_"] selectedImage:[UIImage imageNamed:@"jiaoliu_1"]];
    
    chatListController = [[ChatListController alloc]init];
    chatNav = [[MyNavigationController alloc] initWithRootViewController:chatListController];
    chatListController.navigationItem.title = @"交流群";
    //chatListViewController.setUnreadCountDelegate = self;
    chatNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"交流群" image:[UIImage imageNamed:@"jiaoliu_"] selectedImage:[UIImage imageNamed:@"jiaoliu_1"]];
    
    MineViewController * mineViewController = [[MineViewController alloc]init];
    MyNavigationController * mineNav = [[MyNavigationController alloc] initWithRootViewController:mineViewController];
    mineNav.navigationItem.title = @"我的";
    mineNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:[UIImage imageNamed:@"wode_"] selectedImage:[UIImage imageNamed:@"wode_1"]];
    
    _tabbarController = [[UITabBarController alloc]init];
    _tabbarController.viewControllers = @[mainNav,chatNav,mineNav];
    
    //self.window.rootViewController = _tabbarController;
}

-(void)didLoginFromOtherDevice
{
    
    alertQuit = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您的账号已被其他设备登陆,请重新登陆或修改密码" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    alertQuit.tag = 10001;
    [alertQuit show];
}

#pragma mark - alert
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
            if (!error && info) {
                
                [[User sharedUser] setUserInfo:nil];
                [[EMSDImageCache sharedImageCache] clearDisk];
                
                [[EMSDImageCache sharedImageCache] clearMemory];
                
                NSLog(@"退出成功");
            }
        } onQueue:nil];
        
        exit(0);
    }
    
    
}

#pragma mark - private

-(void)registerNotifications
{
    [self unregisterNotifications];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
}

#pragma mark - call

- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    if (!bCanRecord) {
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:@"未获得授权使用麦克风" message:@"请在iOS\"设置中\"-\"隐私\"-\"麦克风\"中打开" delegate:self cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
        [alt show];
    }
    
    return bCanRecord;
}

- (void)callOutWithChatter:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![self canRecord]) {
            return;
        }
        
        EMError *error = nil;
        NSString *chatter = [object objectForKey:@"chatter"];
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        if (type == eCallSessionTypeAudio) {
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatter timeout:50 error:&error];
        }
        else if (type == eCallSessionTypeVideo){
            if (![CallViewController canVideo]) {
                return;
            }
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatter timeout:50 error:&error];
        }
        
        if (callSession && !error) {
            [[EaseMob sharedInstance].callManager removeDelegate:self];
            
            CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
            callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [chatListController presentViewController:callController animated:NO completion:nil];
        }
        
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
}

- (void)callControllerClose:(NSNotification *)notification
{
    //    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    //    [audioSession setActive:YES error:nil];
    
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    if (chatListController) {
        if (unreadCount > 0) {
            chatNav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
             [self sendPushIfReceiveMessage:unreadCount];
            
        }else{
            chatNav.tabBarItem.badgeValue = nil;
        }
    }
    
//    [self sendPushIfReceiveMessage:unreadCount];
   
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
    
}

//- (void)setUnreadCount:(NSInteger)count {
//    if (count>0) {
//        chatNav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)count];
//    }
//    
//}
- (void)setUnreadInfoCount:(NSInteger)ret {
    chatNav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)ret];
//    [self sendPushIfReceiveMessage:ret];

}
//-----------------------------------------------------------

#pragma mark --------------------自己写的极光推送-----------
- (void)sendPushIfReceiveMessage:(NSInteger)unreadCount{

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
            {
                _notification = [APService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:10]
                                                      alertBody:@"新消息"
                                                          badge:(int)unreadCount
                                                    alertAction:@"确定"
                                                  identifierKey:@"infomation"
                                                       userInfo:nil
                                                      soundName:@"sound.caf"
                                                         region:nil
                                             regionTriggersOnce:YES
                                                       category:nil];
            }
            else
            {
                _notification =[APService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:10]
                                                     alertBody:@"新消息"
                                                         badge:(int)unreadCount
                                                   alertAction:@"确定"
                                                 identifierKey:@"infomation"
                                                      userInfo:nil
                                                     soundName:@"sound.caf"];
            }
            
            NSString *result;
            if(_notification){
                result = @"设置本地通知成功";
            }else{
                result = @"设置本地通知失败";
            }
}

#pragma mark --------------------环信方法-----------------
- (void)setupUntreatedApplyCount {
    
    NSInteger unreadCount = [[[ApplyViewController shareController] dataSource] count];
    
    if (unreadCount > 0) {
        chatNav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
        
       
    }else{
        chatNav.tabBarItem.badgeValue = nil;
    }
    
}


// 得到未读消息条数
- (NSInteger)unreadMessageCountByConversation:(EMConversation *)conversation
{
    NSInteger ret = 0;
    ret = conversation.unreadMessagesCount;
    NSLog(@"dedede到未读消息%ld",(long)ret);
    
    if (ret > 0) {
        [self setUnreadInfoCount:ret];
    }
    
    return  ret;
}
//// 统计未读消息数
//-(void)setupUnreadMessageCount
//{
//    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
//    NSInteger unreadCount = 0;
//    for (EMConversation *conversation in conversations) {
//        unreadCount += conversation.unreadMessagesCount;
//    }
//    if (chatListViewController) {
//        if (unreadCount > 0) {
//            chatNav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
//        }else{
//            chatNav.tabBarItem.badgeValue = nil;
//        }
//    }
//    
//    UIApplication *application = [UIApplication sharedApplication];
//    [application setApplicationIconBadgeNumber:unreadCount];
//}

#pragma mark - IChatManagerDelegate 消息变化

- (void)didUpdateConversationList:(NSArray *)conversationList
{
    [self setupUnreadMessageCount];
    [chatListController refreshDataSource];
}

// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [APService resetBadge];
    [self setupUnreadMessageCount];
    
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages
{
    [self setupUnreadMessageCount];
    
}

- (void)didFinishedReceiveOfflineCmdMessages:(NSArray *)offlineCmdMessages
{
    
}

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    return ret;
}

// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        
        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
        if (!isAppActivity) {
//            [self showNotificationWithMessage:message];
        }else {
           // [self playSoundAndVibration];
        }
#endif
    }
    
    
}

//-(void)didReceiveCmdMessage:(EMMessage *)message
//{
//    [self showHint:NSLocalizedString(@"receiveCmd", @"receive cmd message")];
//}
//
//- (void)playSoundAndVibration{
//    NSTimeInterval timeInterval = [[NSDate date]
//                                   timeIntervalSinceDate:self.lastPlaySoundDate];
//    if (timeInterval < kDefaultPlaySoundInterval) {
//        //如果距离上次响铃和震动时间太短, 则跳过响铃
//        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
//        return;
//    }
//    
//    //保存最后一次响铃时间
//    self.lastPlaySoundDate = [NSDate date];
//    
//    // 收到消息时，播放音频
//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//    // 收到消息时，震动
//    [[EMCDDeviceManager sharedInstance] playVibration];
//}

//- (void)showNotificationWithMessage:(EMMessage *)message
//{
//    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
//    //发送本地推送
//    UILocalNotification *notification = [[UILocalNotification alloc] init];
//    notification.fireDate = [NSDate date]; //触发通知的时间
//    
//    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
//        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
//        NSString *messageStr = nil;
//        switch (messageBody.messageBodyType) {
//            case eMessageBodyType_Text:
//            {
//                messageStr = ((EMTextMessageBody *)messageBody).text;
//            }
//                break;
//            case eMessageBodyType_Image:
//            {
//                messageStr = NSLocalizedString(@"message.image", @"Image");
//            }
//                break;
//            case eMessageBodyType_Location:
//            {
//                messageStr = NSLocalizedString(@"message.location", @"Location");
//            }
//                break;
//            case eMessageBodyType_Voice:
//            {
//                messageStr = NSLocalizedString(@"message.voice", @"Voice");
//            }
//                break;
//            case eMessageBodyType_Video:{
//                messageStr = NSLocalizedString(@"message.vidio", @"Vidio");
//            }
//                break;
//            default:
//                break;
//        }
//        
//        NSString *title = message.from;
//        if (message.messageType == eMessageTypeGroupChat) {
//            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
//            for (EMGroup *group in groupArray) {
//                if ([group.groupId isEqualToString:message.conversationChatter]) {
//                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
//                    break;
//                }
//            }
//        }
//        else if (message.messageType == eMessageTypeChatRoom)
//        {
//            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
//            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
//            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
//            if (chatroomName)
//            {
//                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
//            }
//        }
//        
//        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
//    }
//    else{
//        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
//    }
//    
//#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
//    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
//    
//    notification.alertAction = NSLocalizedString(@"open", @"Open");
//    notification.timeZone = [NSTimeZone defaultTimeZone];
//    notification.soundName = UILocalNotificationDefaultSoundName;
//    
//    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
//    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
//    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
//    notification.userInfo = userInfo;
//    
//    //发送通知
//    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//    //    UIApplication *application = [UIApplication sharedApplication];
//    //    application.applicationIconBadgeNumber += 1;
//}
//


//- (void)networkChanged:(EMConnectionState)connectionState
//{
//    _connectionState = connectionState;
//    [chatListController networkChanged:connectionState];
//}

// 监听系统生命周期回调，以便将需要的事件传给SDK
- (void)setupNotifiers{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidFinishLaunching:)
                                                 name:UIApplicationDidFinishLaunchingNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActiveNotif:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillResignActiveNotif:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillTerminateNotif:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataWillBecomeUnavailableNotif:)
                                                 name:UIApplicationProtectedDataWillBecomeUnavailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataDidBecomeAvailableNotif:)
                                                 name:UIApplicationProtectedDataDidBecomeAvailable
                                               object:nil];
}
#pragma mark - notifiers
- (void)appDidEnterBackgroundNotif:(NSNotification*)notif{
    DLog(@"进入后台了%@",notif);
    [[EaseMob sharedInstance] applicationDidEnterBackground:notif.object];
    [self setupUnreadMessageCount];
}

- (void)appWillEnterForeground:(NSNotification*)notif
{
    DLog(@"进入后台了%@",notif);
    [[EaseMob sharedInstance] applicationWillEnterForeground:notif.object];
}

- (void)appDidFinishLaunching:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidFinishLaunching:notif.object];
}

- (void)appDidBecomeActiveNotif:(NSNotification*)notif
{
    //    [[EaseMob sharedInstance] applicationDidBecomeActive:notif.object];
}

- (void)appWillResignActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillResignActive:notif.object];
}

- (void)appDidReceiveMemoryWarning:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidReceiveMemoryWarning:notif.object];
}

- (void)appWillTerminateNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillTerminate:notif.object];
}

- (void)appProtectedDataWillBecomeUnavailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataWillBecomeUnavailable:notif.object];
}

- (void)appProtectedDataDidBecomeAvailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataDidBecomeAvailable:notif.object];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



@end
